﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GameViewer.Core.Archives;
using System.IO;

namespace GameViewer.Ogre
{
    public class OgreMaterialManager : GameViewer.Core.Singleton<OgreMaterialManager>
    {
        Dictionary<string, OgreMaterial> mMaterials;
        List<string> mLoadedArchives;

        public OgreMaterialManager()
        {
            mMaterials = new Dictionary<string, OgreMaterial>();
            mLoadedArchives = new List<string>();
        }

        public void AddMaterial(OgreMaterial material)
        {
            if (mMaterials.ContainsKey(material.Name) == false)
            {
                mMaterials.Add(material.Name, material);
            }
        }

        public OgreMaterial GetMaterial(string name)
        {
            if (mMaterials.ContainsKey(name))
            {
                return mMaterials[name];
            }

            //解析
            foreach (KeyValuePair<string,Archive> kvp in ArchiveManager.Instance.Archives)
            {
                Archive archive = kvp.Value;
                LoadArchive(archive);
            }
            
            //返回
            if (mMaterials.ContainsKey(name))
            {
                return mMaterials[name];
            }
            else
            {
                return null;
            }
        }

        private void LoadArchive(Archive archive)
        {
            if (mLoadedArchives.Contains(archive.Name))
            {
                return;
            }
            mLoadedArchives.Add(archive.Name);

            OgreMaterialSerializer ms = new OgreMaterialSerializer();
            List<GameViewer.Core.Archives.FileInfo> fileInfos = archive.FindFileInfo(".material");
            foreach (GameViewer.Core.Archives.FileInfo fileInfo in fileInfos)
            {
                Stream stream = fileInfo.Archive.Open(fileInfo.FileName);
                ms.ParseScript(stream, fileInfo.FileName);
                stream.Close();
            }
        }
    }
}
